package com.jeesite.modules.dataScreen.service;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.jeesite.modules.dataScreen.web.vo.alarm.HotConcernCurrentVo;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service
public class HotConcernCurrenCacheService {

    public static HotConcernTimer totalTimer = new HotConcernTimer();
    public static HotConcernTimer tsTimer = new HotConcernTimer();
    @Resource
    HotConcernService hotConcernService;

    LoadingCache<String, HotConcernCurrentVo> loadingCache;

    @PostConstruct
    public void init() {
        loadingCache = CacheBuilder.newBuilder()
                // 设置并发级别为8，并发级别是指可以同时写缓存的线程数
                .concurrencyLevel(4)
                // 设置写缓存后过期时间
                .expireAfterWrite(180, TimeUnit.SECONDS)
                // 设置缓存容器的初始容量
                .initialCapacity(2)
                // 设置缓存最大容量,超过最大容量之后就会按照LRU最近虽少使用算法来移除缓存项
                .maximumSize(2)
                // 设置要统计缓存的命中率
                .recordStats()
                //当获取缓存不存在时, 默认执行
                .build(new CacheLoader<String, HotConcernCurrentVo>() {
                    @Override
                    public HotConcernCurrentVo load(String key) {
                        return hotConcernService.getHotConcernCurrent();
                    }
                });
    }

    public HotConcernCurrentVo getHotConcernCurrentVo() {
        try {
            HotConcernCurrentVo currentVo = loadingCache.get("");
            if (Objects.nonNull(currentVo)) {
                Long total = totalTimer.get();
                if (Objects.nonNull(total)) {
                    currentVo.setTotal(total);
                }
                Long ts = tsTimer.get();
                if (Objects.nonNull(ts)) {
                    currentVo.setComplain(ts);
                }
                if (Objects.nonNull(total) && Objects.nonNull(ts) && ts > 0) {
                    currentVo.setComplainRatio(BigDecimal.valueOf(ts * 100).divide(BigDecimal.valueOf(total), BigDecimal.ROUND_DOWN, RoundingMode.DOWN));
                }
                return currentVo;
            }
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

}
